<?php
namespace Tiger;

use Tiger\Libs\Config;
class Tiger
{
	/**
	 * Tiger唯一实例
	 */
	public static $app = null;
	
	/**
	 * 应用程序根目录
	 */
	public static $app_path = '';
	
	/**
	 * Tiger 对象池
	 */
	protected $objects = array();
	
	/**
	 * factory_key
	 */
	public $factory_key = 'master';
	
	/**
	 * 配置文件对象
	 */
	public $config = array();
	
	/**
	 * 多实例模型
	 */
	
	public static $multi_instance = array(
		'redis' => true
	);
	/**
	 * pid文件
	 */
	protected static $_pidFile = '';
	
	public function __construct()
	{
		$this->config = new Config();
	}
	
	/**
	 * 设置配置文件目录
	 * @param $path
	 */
	public static function setConfigPath($path, $alias)
	{
		Tiger::getInstance()->config->setPath(realpath($path), $alias);
	}
	
	/**
	 * 设置AppsPath
	 * @param $path
	 */
	public static function setAppsPath($path)
	{
		if (empty(Tiger::$app_path) && is_dir($path)) 
		{
			$_path = realpath($path);
			Tiger::$app_path = $_path;
			Loader::addNameSpace('App', $_path);
		}
	}
	/**
	 * 设置pid文件
	 * @param $file
	 */
	public static function setPidFile($file)
	{
		self::$_pidFile = $file;
	}
		
	/**
	 * 参数解析
	 */
	public function parseCommand()
	{
		global $argv;
		$command = $argv;
		
		$start_file = $command[0];
		if (!isset($command[1]))
		{
			echo "Usage: php yourfile.php {start|stop|restart|reload|status|kill}\n";
			exit(1);
		}		
	}
	
	/**
	 * 获取Tiger实例
	 * @return \Tiger\Tiger
	 */
	public static function getInstance()
	{
		if (empty(self::$app))
			self::$app = new Tiger();
		return self::$app;
	}
	
	/**
	 * Tiger组件/模型加载
	 * @param $lib_name
	 */
	public function __get($lib_name)
	{
		echo $lib_name;
	}
	
	/**
	 * Tiger组件/模型加载
	 * @param $func
	 * @param $args
	 */
	public function __call($func, $param)
	{
		if (empty($param[0]) || !is_string($param[0]))
	    {
			throw new \Exception("module key cannot be null.");
	    }
	    return $this->loadModule($func,$param[0]);
	}
	
	/**
	 * 组件模型加载
	 */
	protected function loadModule($module, $key = 'master')
	{
		$module_id = $module . '_' . $key;
		if (!isset($this->objects[$module_id]) || empty($this->objects[$module_id])) 
		{
			$object = new \stdClass();
			$this->factory_key = $key;
			// 加载用户模型
			$user_factory_file = Tiger::$app_path . '/Factory/' . $module . '.php';
			if (is_file($user_factory_file)) 
			{
				$object = require_once $user_factory_file;
				 
			}
			else 
			{
				// 系统默认模型
				$tiger_factory_file = LIBPATH . '/Factory/' . $module . '.php';
				if (!is_file($tiger_factory_file))
				{
					throw new \Exception('Module ' . $module . ' Not Find');
				}
				$object = require_once $tiger_factory_file;
			}
			$this->objects[$module_id] = $object;
		}
		return $this->objects[$module_id];
	}
	
	
}